package com.bw.controller;

import com.bw.entity.Dict;
import com.bw.entity.StudentAdd;
import com.bw.entity.StudentQuery;
import com.bw.entity.StudentRoom;
import com.bw.mapper.StudentMapper;
import com.bw.service.StudentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.spring.kun.common.ExcelUtils;
import org.spring.kun.common.ZzyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

@Controller
public class StudentController {

    @Autowired
    StudentMapper studentMapper;
    @Autowired
    StudentService studentService;

    @RequestMapping("/list.do")
    public String list(StudentQuery query, Integer pageNum, Model model) {

        //1.分页查询
        PageHelper.startPage(pageNum == null ? 1 : pageNum, 20);
        List<StudentRoom> list = studentMapper.selectList(query);
        PageInfo<StudentRoom> pageInfo = new PageInfo<>(list);
        model.addAttribute("pageInfo", pageInfo);

        // 条件不丢失
        model.addAttribute("query",query);

        return "list";
    }


    @RequestMapping("/excelList.do")
    public void excel(StudentQuery query, HttpServletResponse response){
        List<StudentRoom> list = studentMapper.selectList(query);

        ExcelUtils.exportExcel(list,"学生宿舍导出","sheet1",response);
    }

    @RequestMapping("addPage.do")
    public String addPage(Model model){
        //1 添加页面的三个下拉框

        List<Dict> stuList = studentMapper.studentList();
        model.addAttribute("stuList",stuList);
        List<Dict> roomList = studentMapper.roomList();
        model.addAttribute("roomList",roomList);
        List<Dict> apartmentList = studentMapper.apartmentList();
        model.addAttribute("apartmentList",apartmentList);
        return "add";
    }

    @RequestMapping("/add.do")
    public String add(@Valid StudentAdd studentAdd , BindingResult result,Model model){

        if (result.hasErrors()){
            model.addAttribute("error",result.getAllErrors().get(0).getDefaultMessage());
            List<Dict> stuList = studentMapper.studentList();
            model.addAttribute("stuList",stuList);
            List<Dict> roomList = studentMapper.roomList();
            model.addAttribute("roomList",roomList);
            List<Dict> apartmentList = studentMapper.apartmentList();
            model.addAttribute("apartmentList",apartmentList);
            return "add";
        }

        studentService.add(studentAdd);

        boolean b = ZzyUtils.sendSms("17611221735", "你入住成功了", 5);

        return "redirect:list.do";
    }


}
